﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DataController.ViewModels;
using Primitive.Mvvm.Framework.Interfaces;

namespace UIController.Views
{
    public partial class TaskIssueDateView : UserControl, IWindowContainer
    {
        private TaskDetailsViewModel _model;
        public TaskIssueDateView()
        {
            InitializeComponent();
            reminder.ValueChanged += OnReminderValueChanged;
        }

        public bool Initialize(IModel model, IMediator mediator, List<Exception> exceptions)
        {
            _model = new TaskDetailsViewModel(model, mediator);
            reminder.MinDate = _model.MinDate;
            reminder.MaxDate = _model.MaxDate;

            _model.RefreshViewFunc = OnRefresh;
            return Refresh(exceptions);
        }

        private bool Refresh(List<Exception> exceptions)
        {
            reminder.Value = _model.TaskIssueDate;
            return true;
        }

        private bool OnRefresh(IViewCallback arg)
        {
            if (!_model.CanRefreshView(arg))
                return false;

            var listExc = new List<Exception>();
            var res = Refresh(listExc);
            if (listExc.Count > 0)
            {
                var ecx = new AggregateException("Refresh exception in BottomView", listExc);
                throw ecx;
            }

            return res;
        }

        private void OnReminderValueChanged(object sender, EventArgs e)
        {
            _model.TaskIssueDate = reminder.Value;
        }

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                reminder.ValueChanged -= OnReminderValueChanged;
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        public void Clear(out Exception exception)
        {
            exception = null;
            _model = null;
        }
    }
}
